<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 健康小屋逻辑
 */
class Activity extends LogicBase
{
    
    /**
     * 获取健康小屋列表
     */
    public function getActivityList($where = [], $field = true, $order = '', $paginate = 0)
    {
        $this->modelActivity->alias('a');
        $join=[['my_healthroom h','a.room_id=h.room_id']];
        $field='a.*, h.name as healthroom';   
        return $this->modelActivity->getList($where, $field, $order, $paginate,$join);
    }


    public function activityEdit($data = [])
    {
        $validate_result = $this->validateActivity->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateActivity->getError()];
        }
        
        $url = url('workplanList',['room_id'=>$data['room_id']]);

        $result = $this->modelActivity->setInfo($data);
        
        $handle_text = empty($data['id']) ? '新增' : '编辑';
        
        $result && action_log($handle_text, 'Activity' . $handle_text . '，plan_content：' . $data['plan_content']);
        
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelActivity->getError()];
    }

    public function activityDel($where = [])
    {
        
        $result = $this->modelActivity->deleteInfo($where);
        
        $result && action_log('删除', '活动删除' . '，where：' . http_build_query($where));
        
        return $result ? [RESULT_SUCCESS, '删除成功'] : [RESULT_ERROR, $this->modelActivity->getError()];
    }

    /**
     * 获取活动信息
     */
    public function getActivityInfo($where = [], $field = true)
    {
        
        return $this->modelActivity->getInfo($where, $field);
    }


    /**
     * 获取健康小屋信息
     */
    public function getHealthroomInfo($where = [], $field = true)
    {
        
        return $this->modelHealthroom->getInfo($where, $field);
    }
    
   
    public function activityReminder($value='')
    {
        # code...
    }


    /**
     * 近期活动列表
     */
    public function getLastActivityList($county_id=0)
    {
        $this->modelActivity->alias('a');
        $join=[['my_healthroom h','a.room_id=h.room_id']];
        $where=['h.room_id'=>$county_id,'a.plan_time'=>['gt',TIME_NOW]];
        $field='a.*, h.name as healthroom';
        return $this->modelActivity->getList($where,$field,'',0,$join);
    }
    
    /**
     * 专家近期活动列表
     */
    public function getLastExpertActivityList($professor_code=0)
    {
        $this->modelActivity->alias('a');
        $join=[['my_healthroom h','a.room_id=h.room_id'],['member m','a.professor_code=m.username']];
        $where=['a.professor_code'=>$professor_code,'a.plan_time'=>['gt',TIME_NOW]];
        $field='a.*, h.name as healthroom,m.nickname as nickname';
        return $this->modelActivity->getList($where,$field,'',0,$join);
    }

    public function lastActivityEdit($data = [])
    {
        
        $validate_result = $this->validateActivity->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateActivity->getError()];
        }
        
        $url = url('lastExpertActivityList');
        
        $result = $this->modelActivity->setInfo($data);
        
        $handle_text = empty($data['id']) ? '新增' : '编辑';
        
        $result && action_log($handle_text, 'Activity' . $handle_text . '，plan_content：' . $data['plan_content']);
        
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelActivity->getError()];
    }

/**
 * 7天后，自动计算ActivityDetail中的评价数据到Activity中
 * @return [type] [description]
 */
private function calculateActivityDetail()
{
        // return $this->modelActivityDetail->execute('update ob_my_activity a,
        // (select activity_id,sum(pcount) as pcount,sum(gcount) as gcount,avg(attitude) as attitude,avg(capacity) as capacity,avg(quality) as quality,
        // avg(efficiency) as efficiency,avg(discipline) as discipline from ob_my_activity_detail group by activity_id) b
        //  set a.pcount=b.pcount,a.gcount=b.gcount,a.attitude=b.attitude,a.capacity=b.capacity,a.quality=b.quality,a.efficiency=b.efficiency,a.discipline=b.discipline,a.activity_status=1
        //   where a.id=b.activity_id and a.activity_status=0 and datediff(a.plan_time,now())>7');

                return $this->modelActivityDetail->execute('update ob_my_activity a,
        (select activity_id,sum(pcount) as pcount,sum(gcount) as gcount,avg(attitude) as attitude,avg(capacity) as capacity,avg(quality) as quality,
        avg(efficiency) as efficiency,avg(discipline) as discipline from ob_my_activity_detail group by activity_id) b
         set a.pcount=b.pcount,a.gcount=b.gcount,a.attitude=b.attitude,a.capacity=b.capacity,a.quality=b.quality,a.efficiency=b.efficiency,a.discipline=b.discipline,a.activity_status=1
          where a.id=b.activity_id and a.activity_status=0');
}

    /**
     * 【卫计委】对小屋进行活动评价,先计算，再列表显示
     */
        public function getHealthroomEvaluationListForCommission()
        {
         //首先将活动明细表中信息进行汇总，写入到活动表中，
       $result=$this->calculateActivityDetail();
       
       //区域信息读取
       $type=session('department_info')['type'];
       $county_id=session('department_info')['county_id'];
       $town_id=session('department_info')['town_id'];
            //小屋活动信息，join小屋，join区划信息
        $this->modelActivity->alias('a');

        $field='r.name region_name,rm.name room_name,sum(pcount) pcount,avg(attitude) attitude,avg(capacity) capacity,avg(quality) quality,avg(efficiency) efficiency,avg(discipline) discipline';
       if($type==0 && $county_id=='130400')
       {
                $where=['r.level'=>'1','a.activity_status'=>1];
                $group='r.name,rm.name';
                $order='r.id,rm.name';
          $join=[['my_healthroom rm','a.room_id=rm.room_id','right'],['region r','r.id=rm.county_id']];
            }elseif($type==0 && $county_id!='130400')
            {


                $where=['r.level'=>'2','rm.county_id'=>$county_id,'a.activity_status'=>1];
                $group='r.name,rm.name';
                $order='rm.town_id,rm.name';
                $join=[['my_healthroom rm','a.room_id=rm.room_id','right'],['region r','r.id=rm.town_id']];
               $field='r.name region_name,rm.name room_name,sum(pcount) pcount,avg(attitude) attitude,avg(capacity) capacity,avg(quality) quality,avg(efficiency) efficiency,avg(discipline) discipline';
            }else
            {
              return $this->modelActivity->getList(['id'=>-1]);
            }
        $list=$this->modelActivity->getList($where,$field,$order,20,$join,$group);
        return $list;

        }
    /**
     * 【医院】对小屋进行活动评价,先计算，再列表显示
     */
        public function getHealthroomEvaluationListForHospital()
        {
         //首先将活动明细表中信息进行汇总，写入到活动表中，
       $result=$this->calculateActivityDetail();
       

       $type=session('department_info')['type'];
       $hospital_id=session('department_info')['id'];

if($type==1)
{
    $where=['rm.hospital_id'=>$hospital_id];
}else
{
    return $this->modelActivity->getList(['id'=>-1]);
}
            //小屋活动信息，join小屋，join区划信息
        $this->modelActivity->alias('a');
        $join=[['my_healthroom rm','a.room_id=rm.room_id'],['region r','r.id=rm.county_id']];
        $field='r.name region_name,rm.name room_name,rm.owner_name owner_name,sum(pcount) pcount,avg(attitude) attitude,avg(capacity) capacity,avg(quality) quality,avg(efficiency) efficiency,avg(discipline) discipline';
        $group='r.id';

        $order='r.id,rm.name';
        $list=$this->modelActivity->getList($where,$field,$order,20,$join,$group);
        return $list;

        }

    /**
     * 首页小屋接诊病患人次
     */
    public function getPersonListForCount($where = [], $field = true, $order = '', $paginate = 20000)
    {
       
      $field='sum(pcount) countnumber';
      $list=$this->modelActivity->getList($where,$field,$order,$paginate);
       return $list['0']['countnumber'];
    }


}
